import logging

from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request
from flask import session

from info import constants
from info.models import User, News, Category
from info.utils.commons import user_login_data
from info.utils.response_code import RET
from . import index_blue


@index_blue.route('/newslist')

def news_list():

    cid = request.args.get("cid", "1")

    page = request.args.get("page", "1")

    per_page = request.args.get("per_page", "10")

    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
        per_page = 10

    try:
        filters = [News.status ==0]
        if cid != "1":
            filters.append(News.category_id == cid)

        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="新闻获取失败")

    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items

    newsList = []
    for item in items:
        newsList.append(item.to_dict())

    return jsonify(errno=RET.OK, errmsg="获取成功", totalPage=totalPage, currentPage=currentPage, newsList=newsList)


@index_blue.route("/")
@user_login_data
def show_index():
    # user_id = session.get("user_id")
    #
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)

    try:
        news = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="新闻查询失败")
    click_news_list = []
    for new in news:
        click_news_list.append(new.to_dict())

    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="分类查询失败")
    category_list = []
    for category in categories:
        category_list.append(category.to_dict())

    data = {
        "user_info": g.user.to_dict() if g.user else "",
        "click_news_list": click_news_list,
        "category_list": category_list

    }

    return render_template("news/index.html", data=data)


@index_blue.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')
